import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQBytesMessage;

import javax.jms.*;

/**
 * @author: blentle
 * @group: rd
 * @createdate: 2018/4/22 0022 下午 23:15
 * @mail: blentle.huan.ren@gmail.com
 * @description: quick  sort
 * @since: 1.0
 */
public class Subscriber {

    private static String brokerUrl = "tcp://www.blentle.top:61616";
    private static final String TOPIC = "jack_mqtt_test";

    public void start() {
        // 消费者的主要流程
        Connection connection = null;
        try {
            // 1.初始化connection工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

            // 2.创建Connection
            connection = connectionFactory.createConnection();


            connection.setClientID("blentle.huan.ren@gmail.com");

            // 3.打开连接
            connection.start();

            // 4.创建session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // 5.创建消息目标
            Destination destination = session.createTopic(TOPIC);

            // 6.创建消费者
            MessageConsumer consumer = session.createConsumer(destination);
            while(true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = consumer.receive();
                if(message instanceof ActiveMQBytesMessage) {
                    ActiveMQBytesMessage msg = (ActiveMQBytesMessage)message;
                    try {
                        long length = msg.getBodyLength();
                        byte device = msg.readByte();
                        System.err.println("total" + length + ": " + device);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("error msg type");
                }
            }
            // 7.配置监听
//            consumer.setMessageListener(message -> {
//                if(message instanceof ActiveMQBytesMessage) {
//                    ActiveMQBytesMessage msg = (ActiveMQBytesMessage)message;
//                    try {
//                        long length = msg.getBodyLength();
//                        byte device = msg.readByte();
//                        System.err.println("..........");
//                    } catch (JMSException e) {
//                        e.printStackTrace();
//                    }
//                } else {
//                    System.err.println("error msg type");
//                }
//            });

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Subscriber().start();
    }
}
